#!/usr/bin/bash

# Copyright (c) 2022. Huawei Technologies Co.,Ltd.ALL rights reserved.
# This program is licensed under Mulan PSL v2.
# You can use it according to the terms and conditions of the Mulan PSL v2.
#          http://license.coscl.org.cn/MulanPSL2
# THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
####################################
#@Author        :   zhujinlong
#@Contact       :   zhujinlong@163.com
#@Date          :   2020-07-24
#@License       :   Mulan PSL v2
#@Desc          :   Application scenarios: encrypt and decrypt the file asymmetrically using RSA algorithm
#####################################

source ${OET_PATH}/libs/locallibs/common_lib.sh

function run_test() {
    LOG_INFO "Start to run test."
    cat >plain.txt <<EOF
    This is a file created by shell.
    We want to make a good world.   
    Byebye!
EOF
    openssl genrsa -out rsaprivatekey.pem -passout pass:trousers -des3 2048
    CHECK_RESULT $?
    grep 'BEGIN RSA PRIVATE KEY' rsaprivatekey.pem
    CHECK_RESULT $?
    openssl rsa -in rsaprivatekey.pem -passin pass:trousers -pubout -out rsapublickey.pem
    CHECK_RESULT $?
    grep 'BEGIN PUBLIC KEY' rsapublickey.pem
    CHECK_RESULT $?
    openssl rsautl -encrypt -pubin -inkey rsapublickey.pem -in plain.txt -out cipher.txt
    CHECK_RESULT $?
    test -f cipher.txt
    CHECK_RESULT $?
    expect <<-END
    log_file testlog1
    spawn openssl rsautl -decrypt -inkey rsaprivatekey.pem -in cipher.txt -out plain_back.txt
    expect "Enter pass phrase for rsaprivatekey.pem:"
    send "trousers\\n"
    expect eof
    exit
END
    grep 'rsaprivatekey.pem' testlog1
    CHECK_RESULT $?
    diff plain.txt plain_back.txt
    CHECK_RESULT $?
    expect <<-END
    log_file testlog2
    spawn openssl rsautl -sign -inkey rsaprivatekey.pem -in plain.txt -out signature.bin
    expect "Enter pass phrase for rsaprivatekey.pem:"
    send "trousers\\n"
    expect eof
    exit
END
    grep 'rsaprivatekey.pem' testlog2
    CHECK_RESULT $?
    test -f signature.bin
    CHECK_RESULT $?
    openssl rsautl -verify -pubin -inkey rsapublickey.pem -in signature.bin -out signature_verify.bin
    CHECK_RESULT $?
    test -f signature_verify.bin
    CHECK_RESULT $?
    diff plain.txt signature_verify.bin
    CHECK_RESULT $?
    LOG_INFO "End to run test."
}

function post_test() {
    LOG_INFO "Start to restore the test environment."
    rm -f $(ls | grep -v "\.sh\|common")
    LOG_INFO "End to restore the test environment."
}

main "$@"
